package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Employee;
import com.itheima.reggie.service.EmployeeService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 员工管理模块
 */
@Slf4j
@RestController //@Controller+@ResposeBody
@RequestMapping("employee")
@Api(tags = "员工模块")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    //员工登录
//    @PostMapping("login")
//    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
//        String username = employee.getUsername();
//        String password = employee.getPassword();
//
//        // 1. 先根据用户名查询
//        Employee e = employeeService.lambdaQuery()
//                .eq(Employee::getUsername, username)
//                .one();
//        if (e == null) {
//            //说明账号不存在
//            return R.error("账号不存在");
//        }
//        // 2. 判断密码是否一致
//        if (!StringUtils.equals(e.getPassword(), DigestUtils.md5DigestAsHex(password.getBytes()))) {
//            //说明密码错误
//            return R.error("密码错误");
//        }
//        // 3. 判断用户状态
//        if (e.getStatus() == 0) {
//            //说明账号已被禁用
//            return R.error("账号已被禁用");
//        }
//        //4. 说明登录成功，一定要将用户存入session中
//        session.setAttribute("employee", e.getId());
//        return R.success(e);
//    }


//    //员工退出
//    @PostMapping("logout")
//    public R<String> logout(HttpSession session) {
//        //1. 删除session中的用户信息，销毁session对象
//        //session.removeAttribute("employee");
//        session.invalidate();
//        //2. 返回成功标识 code=1
//        return R.success("退出成功");
//    }

    //员工登录
    @PostMapping("login")
    @ApiOperation("员工登录")
    public R login(@RequestBody Employee employee,HttpSession session ){
        String username = employee.getUsername();
        String password = employee.getPassword();

        //1.首先根据用户名查询//1.首先根据用户名查询
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee e = employeeService.getOne(queryWrapper);
        //TODO 另一种风格
        Employee ee = employeeService.query()
            .eq("username", employee.getUsername())
            .one();
        //TODO 另另一种风格
        Employee eee = employeeService
            .lambdaQuery()
            .eq(Employee::getUsername, employee.getUsername())
            .one();

        if(ee == null){
            //说明账号不存在
            return R.error("账号不存在");
        }
        //2.判断密码是否一致
       if(!StringUtils.equals(ee.getPassword(),DigestUtils.md5DigestAsHex(password.getBytes()))){
           return R.error("密码错误");
       }
        //3.判断用户状态是否为启用(1)
        if(ee.getStatus() == 0){
            return R.error("账号已被禁用");
        }

        //4.登录成功,一定要将用户加入到对话（session）中
        session.setAttribute("employee",ee.getId());
        return R.success(ee);
    }

    //退出
    @PostMapping("logout")
    public R<String> logout(HttpSession session){
        //1.清理session数据，销毁session对象
//        session.removeAttribute("employee");
        session.invalidate();//直接销毁
        //2.返回成功标识 code=1
        return R.success("退出成功");
    }


    //添加员工
    @PostMapping
    public R save(@RequestBody Employee employee,HttpSession session){
        //密码
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        //创建时间
        employee.setCreateTime(LocalDateTime.now());
        //修改时间
        employee.setUpdateTime(LocalDateTime.now());
        Long employeeId = (Long)session.getAttribute("employee");
        employee.setCreateUser(employeeId);
        employee.setUpdateUser(employeeId);
        //将新员工添加到数据库中
        employeeService.save(employee);

        return R.success("添加成功");
    }

    //分页查询
    @GetMapping("page")
    @ApiOperation("分页查询")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "page",value = "页码"),
        @ApiImplicitParam(name = "pageSize",value = "页面大小"),
        @ApiImplicitParam(name = "name",value = "员工姓名")
    })
    public R<Page<Employee>> page(Integer page,Integer pageSize,String name){
        //1.创建一个分页对象page
        Page<Employee> pageInfo = new Page<>(page,pageSize);
        //2.创建一个条件构造对象

        //分页查询,select * from employee where name = ? order by update_time limit ? ,?
        employeeService.lambdaQuery()
            .like(StringUtils.isNotBlank(name),Employee::getName,name) //过滤条件
            .orderByDesc(Employee::getUpdateTime) //排序条件
            .page(pageInfo);   //分页查询
        //3.响应数据
        return R.success(pageInfo);
    }

    //启用、禁用用户
    @PutMapping
    public R<String> update(@RequestBody Employee employee,HttpSession session){

        log.info("当前线程的id:{}",Thread.currentThread().getId());

        //update employee set status =? ,update_time = ? update_user = ? where id = ?
        //补全员工信息 update_time,update_user
        employee.setUpdateTime(LocalDateTime.now());//设置当前时间
        Long employeeId = (Long)session.getAttribute("employee");
        employee.setUpdateUser(employeeId);//修改操作人

        //修改数据库
        employeeService.updateById(employee);//employee对象中属性为空的会自动忽略
        return R.success("修改成功");
    }

    //根据id查询员工信息
    @GetMapping("{id}")
    public R<Employee> findById (@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        return R.success(employee);
    }




}




